package com.clusterswisdom.horn.api.tmall.action.item;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.db.DbUtil;
import com.clusterswisdom.horn.api.ioc.HornAction;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.clusterswisdom.horn.api.tmall.action.AbstractTmallAction;
import com.clusterswisdom.horn.api.tmall.action.item.event.ItemToSet;
import com.taobao.api.response.ItemQuantityUpdateResponse;
import com.taobao.api.response.ItemUpdateListingResponse;

public class SetItemsNumOfSomeAction extends AbstractTmallAction implements HornAction{
	
	@Override
	public HornResponse execute(ApiConfig config, JSONObject param)
			throws Exception {
	 	Connection con = DbUtil.getUtil().getConnection();
		String sql = "select * from itemsforsetting";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		List<ItemToSet> items = new LinkedList<ItemToSet>();
		while(rs.next()){
			ItemToSet item = new ItemToSet(); 
			item.setItemid(rs.getLong("itemid"));
			item.setNum(rs.getInt("num"));
			items.add(item);
		}
		ps.close();
		DbUtil.getUtil().close();
		if(setNumOfItems(items)){
			
			return new HornResponse(true,"成功");
		}else{
			
			return new HornResponse(false, "失败");
		}
	}
	
	public boolean setNumOfItems(List<ItemToSet> items) {
		boolean hasError = false;
		JSONObject param=new JSONObject();
		
		for(ItemToSet item:items){
				if(item.getNum()>0){
				param.put("num_iid", item.getItemid());
				param.put("num",item.getNum());
				ItemUpdateListingResponse response = null;
				try {
					response = (ItemUpdateListingResponse)TmallInstance.getInstance().executeRequest(param, "item", "itemUpdateListing");
				} catch (Exception e) {
					e.printStackTrace();
				}
				hasError = !response.isSuccess();
			}
		}
		return !hasError;
	}
}
